package com.amon.amonplayer.opengl;

import static android.opengl.EGL14.EGL_CONTEXT_CLIENT_VERSION;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.util.Log;

import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;

public class BaseGLSurfaceView extends GLSurfaceView {
    private EGLContext mEglContext;

    public BaseGLSurfaceView(Context context) {
        super(context, null);
    }

    public BaseGLSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setEGLContextClientVersion(2);
        setEGLContextFactory(new EGLContextFactory() {
            @Override
            public EGLContext createContext(EGL10 egl, EGLDisplay eglDisplay, EGLConfig eglConfig) {
                Log.i("BaseGLSurfaceView", "create Context tid=" + Thread.currentThread().getId());
                int[] attrib_list = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE};
                mEglContext = egl.eglCreateContext(eglDisplay, eglConfig, EGL10.EGL_NO_CONTEXT,
                        attrib_list);
                return mEglContext;
            }

            @Override
            public void destroyContext(EGL10 egl, EGLDisplay eglDisplay, EGLContext eglContext) {
                Log.i("BaseGLSurfaceView", "destroy context tid=" + Thread.currentThread().getId());
                if (!egl.eglDestroyContext(eglDisplay, eglContext)) {
                    Log.e("BaseGLSurfaceView", "display:" + eglDisplay + " context: " + eglContext);
                }
                destroy();
            }
        });
    }

    protected void destroy() {
        Log.i("BaseGLSurfaceView", "destroy context tid=" + Thread.currentThread().getId());
    }

    public EGLContext getEglContext() {
        return mEglContext;
    }
}
